<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\goods\Order;
use app\common\controller\Api;
use app\common\controller\Payment;
use app\common\model\WanlshopGoodsSku;
use think\Controller;
use think\Db;
use think\Request;


class Wanlshopordergoods extends Api
{
    private static $model;
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = model('app\api\model\wanlshop\OrderGoods');
    }

    /**
     * 创建订单的商品清单
     */
    public function create()
    {
        $goods_sku_id = input('goods_sku_id');
        if (!$goods_sku_id) {
            $this->error('参数缺失！');
        }

        $skuInfo = WanlshopGoodsSku::find($goods_sku_id);
        if (!$skuInfo) {
            $this->error('该商品规格不存在！');
        }

        $num = input('num', 1);
        if ($skuInfo->stock < $num) {
            $this->error('该商品规格库存不足！');
        }

        $userId = $this->auth->id;
        $total = round($skuInfo->price * $num, 2);
        $orderNum = create_order($userId);
        $gdata = [
            'user_id' => $userId,
            'order_num' => $orderNum,
            'goods_id' => $skuInfo->goods_id,
            'shop_id' => $skuInfo->goods->shop_id,
            'shop_name' => $skuInfo->goods->shop->shopname,
            'title' => $skuInfo->goods->title,
            'image' => $skuInfo->goods->image,
            'goods_sku_sn' => $skuInfo->sn,
            'goods_sku_id' => $goods_sku_id,
            'difference' => $skuInfo->difference,
            'price' => $skuInfo->price,
            'actual_payment' => $total,
            'number' => $num,
        ];

        $res = self::$model->create($gdata);
        if (!$res->id) {
            $this->error('商品清单表生成失败！');
        }
        $this->success('商品清单表生成成功！', ['order_num' => $orderNum]);
    }

    /**
     * 获取订单的清单
     */
    public function getLists()
    {
        $orderNum = input('order_num');
        if (!$orderNum) {
            $this->error('参数缺失！');
        }

        $lists = self::$model->field('id,shop_name,shop_id,title,image,difference,price,number')->where('order_num', $orderNum)->order('id desc')->select();

        $this->success('清单列表', $lists);
    }
}
